import { defineStore } from "pinia";
import { TodoType, TodoListType } from "../types/todomvc";
import useLocalData from "../hooks/useLocalData";

let useTodoStore = defineStore("todomvc", {
  state: () => {
    return {
      visibility: "all",
      todoList: useLocalData("todomvc").value || [],
    };
  },
  actions: {
    changeVisibility(vis: string) {
      this.visibility = vis;
    },
    delThis(index: number) {
      this.todoList.splice(index, 1);
    },
    addTodo(data: TodoType) {
      this.todoList.push(data);
    },
    changeDone(index: number, flag: boolean) {
      this.todoList[index].done = flag;
    },
    changeAllTodoStatus(flag: boolean) {
      this.todoList.forEach((item) => (item.done = flag));
    },
    EditThis(index: number) {
      this.todoList[index].isEdit = true;
    },
    EditOK(index: number, newTitle: string) {
      this.todoList[index].title = newTitle;
      this.todoList[index].isEdit = false;
    },
    delAll() {
      let res = this.todoList.filter((item) => item.done === false);
      this.todoList.length = 0;
      this.todoList.push(...res);
    },
  },
  getters: {
    // 是否都已完成
    isAllDone(): boolean {
      return this.todoList.every((item) => item.done === true);
    },
    // 统计没有完成todo的数量
    unDoneNumber(): number {
      return this.todoList.filter((item) => item.done === false).length;
    },
    // 筛选不同的todo
    filterTodoList(): TodoListType {
      if (this.visibility === "all") {
        return this.todoList;
      } else if (this.visibility === "active") {
        return this.todoList.filter((item) => item.done === false);
      } else {
        return this.todoList.filter((item) => item.done === true);
      }
    },
  },
});

export default useTodoStore;
